<template>
  <div :style="backgroundStyle">
    <div style="text-align:left;padding:10px">
        <el-button size="mini" icon="el-icon-back" @click="goBack"></el-button>
    </div>
    <Row>
      <Col :sm="{span:12,offset:6}" :md="{span:14,offset:5}" :lg="{span:10,offset:7}">
        <div style="padding:20px">
          <el-card>
            <div slot="header">
              <h2>
                <i class="el-icon-s-management"></i>
                {{ title }}
              </h2>
            </div>
            <!-- 头像文件选择 -->
            <div>
              <div class="demo-basic--circle" style="margin:20px 0">
                <div class="block" >
                  <!-- 头像文件 -->
                  <div style="display:inline-block;width:calc(50% - 10px);">
                    <div @click="userFile.flag = 'portrait';fileClick('portraitFile')">
                      <el-avatar shape="square" icon="el-icon-plus" :size="avatarSize" :src="userFile.portrait.src"
                      style="background:transparent;box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);color:black"></el-avatar>
                      <input :disabled="disabled" ref="portraitFile" type="file" name="file" @change="fileChange" style="display:none"/>
                      <img :src="userFile.portrait.src" style="display:none" ref="portrait" :preview="0">
                      <div slot="tip" class="el-upload__tip">请选择头像文件</div>
                    </div>
                    <el-button plain size="mini" @click="showBig('portrait')" style="margin-top:10px">查看头像大图</el-button>
                  </div>
                  <!-- 个性化背景文件 -->
                  <div style="display:inline-block;width:calc(50% - 10px);">
                    <div @click="userFile.flag = 'background';fileClick('backgroundFile')">
                      <el-avatar shape="square" icon="el-icon-plus" :size="avatarSize" :src="userFile.background.src"
                      style="background:transparent;box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);color:black"></el-avatar>
                      <input :disabled="disabled" ref="backgroundFile" type="file" name="file" @change="fileChange" style="display:none"/>
                      <img :src="userFile.background.src" style="display:none" ref="background" :preview="1">
                      <div slot="tip" class="el-upload__tip">请选择个性背景文件</div>
                    </div>
                    <el-button plain size="mini" @click="showBig('background')" style="margin-top:10px">查看背景大图</el-button>
                  </div>
                </div>
              </div>
              <!-- 文件上传的进度条 -->
              <div v-show="statusFlag">
                <span>{{status}} <i class="el-icon-loading"></i></span>
                <el-progress :percentage="percentage" v-show="progressShow" :text-inside="true" :stroke-width="26" style="margin-top:5px"></el-progress>
              </div>
              <div slot="tip" class="el-upload__tip">只能上传jpg / jpeg / png / gif文件，且不超过20MIB</div>
            </div>
            <div style="margin-top:20px">
              <el-form :rules="rules" label-position="top" ref="userData" :model="userData" status-icon label-width="100px" style="text-align:left">
                    <el-form-item label="昵称" prop="nickname">
                        <el-input :disabled="disabled" v-model="userData.nickname" maxlength=20 show-word-limit placeholder="请输入昵称" style="width:calc(100% - 60px)"></el-input>
                        <el-button size="" plain :disabled="disabledName" :icon="nameIcon" @click="getOneName"></el-button>
                    </el-form-item>
                    <el-form-item label="主页签名">
                        <el-input :disabled="disabled"
                          type="textarea"
                          :autosize="{minRows:5}"
                          v-model="userData.homePublicity"
                          placeholder="请输入主页签名" maxlength=1000 show-word-limit>
                        </el-input>
                    </el-form-item>
                </el-form>
                <el-button size="small" plain :disabled="disabled" @click="updateUserInfo('userData')">确认保存</el-button>
            </div>
          </el-card>
        </div>
      </Col>
    </Row>
    <!-- 弹窗区 -->
    <mt-popup
      v-model="updateThen.flag"
      position="top" style="width:100%">
      <div style="padding:10px">
        <div v-for="(item , index) in updateThen.data" :key="index" style="margin-top:10px">
          <el-tag size="medium" :type="item.type" >{{item.msg}}</el-tag>
        </div>
      </div>
    </mt-popup>
  </div>
</template>

<script>
export default {
  name: 'InfoWrite',
  data () {
    return {
      title: '信息修改',
      avatarSize: 150,
      userData: {
        nickname: '',
        homePublicity: '',
        uid: ''
      },
      userInfo: {},
      backgroundStyle: {},
      rules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { max: 20, message: '最大不可超过20个字符', trigger: 'blur' }
        ]
      },
      userFile: {
        flag: 'portrait',
        portrait: {
          file: null,
          src: ''
        },
        background: {
          file: null,
          src: ''
        }
      },
      disabledName: false,
      nameIcon: 'el-icon-refresh-right',
      disabled: false,
      percentage: 0,
      progressShow: false,
      status: '正在更新个人信息',
      statusFlag: false,
      updateThen: {
        flag: false,
        data: []
      }
    }
  },
  methods: {
    // 读取个人信息
    getUserInfo () {
      this.lseajax.post(this.lseajax.baseurl + '/api/userInfo/getLoginUserInfo', {}).then((data) => {
        if (data.code === 200) {
          this.userInfo = data.data
          this.userFile.portrait.src = data.data.portraitUrl
          this.userFile.background.src = data.data.backgroundImage
          this.userData.uid = data.data.uid
          this.userData.nickname = data.data.nickname
          this.userData.homePublicity = data.data.homePublicity
          this.backgroundStyle = {
            backgroundImage: 'url(' + this.userInfo.backgroundImage + ')',
            backgroundRepeat: 'no-repeat',
            backgroundPosition: 'center center',
            backgroundSize: 'cover'
          }
        } else {
          this.lseutil.msg({
            msg: data.msg
          })
          this.lseajax.storageJson.remove(this.lsedata.tokenName)
          this.lseutil.go('login')
        }
      })
    },
    fileChange (e) {
      let file = e.target.files[0]
      let src = this.lseutil.checkFileIsImage(file)
      if (src) {
        if (this.userFile.flag === 'portrait' && file.size <= 20971520) {
          this.userFile.portrait.file = file
          this.userFile.portrait.src = src
        } else if (this.userFile.flag === 'background' && file.size <= 20971520) {
          this.userFile.background.file = file
          this.userFile.background.src = src
          this.backgroundStyle = {
            backgroundImage: 'url(' + src + ')',
            backgroundRepeat: 'no-repeat',
            backgroundPosition: 'center center',
            backgroundSize: 'cover'
          }
        } else {
          this.lseutil.msg({
            msg: '文件大小不能超过20MIB,已帮您自动清除'
          })
        }
      } else {
        this.lseutil.msg({
          msg: '请选择 jpg / jpeg / png / gif 格式的图片文件'
        })
      }
    },
    // 更新用户信息（用户头像等信息）
    updateUserInfo (formName) {
      this.updateThen.data = []
      this.$refs[formName].validate((value) => {
        if (value) {
          this.disabled = true
          this.statusFlag = true
          this.status = '正在更新个人信息'
          if (this.userFile.portrait.file) {
            this.progressShow = true
          }
          if (!this.userData.homePublicity.trim()) {
            this.userData.homePublicity = '欢迎来到我的主页'
          }
          let formData = new FormData()
          formData.append('file', this.userFile.portrait.file)
          formData.append('nickname', this.userData.nickname)
          formData.append('homePublicity', this.userData.homePublicity)
          formData.append('uid', this.userData.uid)
          this.lseajax.uploadFile(this.lseajax.baseurl + '/api/userInfo/updateUserInfo', formData, this).then((res) => {
            if (res.code === 200) {
              this.updateThen.data.push({
                type: 'success',
                msg: '更新个人信息: ' + res.msg
              })
              if (this.userFile.background.file) {
                this.updateUserInfoPer()
              } else {
                this.updateThen.flag = true
              }
            } else {
              this.updateThen.data.push({
                type: 'warning',
                msg: '更新个人信息: ' + res.msg
              })
              this.lseutil.msg({
                msg: res.msg
              })
            }
            // 清空用户数据
            this.disabled = false
            this.progressShow = false
            this.statusFlag = false
            this.percentage = 0
          }).catch(res => {
            this.disabled = false
            this.statusFlag = false
            this.progressShow = false
            this.percentage = 0
          })
        }
      })
    },
    // 更新个性化背景
    updateUserInfoPer () {
      this.disabled = true
      this.statusFlag = true
      this.status = '正在更新个性化信息'
      if (this.userFile.background.file) {
        this.progressShow = true
      }
      let formData = new FormData()
      formData.append('file', this.userFile.background.file)
      formData.append('uid', this.userData.uid)
      this.lseajax.uploadFile(this.lseajax.baseurl + '/api/userInfo/updateUserInfoPer', formData, this).then((res) => {
        if (res.code === 200) {
          this.updateThen.data.push({
            type: 'success',
            msg: '更新个性化信息: ' + res.msg
          })
        } else {
          this.updateThen.data.push({
            type: 'warning',
            msg: '更新个性化信息: ' + res.msg
          })
          this.lseutil.msg({
            msg: res.msg
          })
        }
        this.updateThen.flag = true
        // 清空用户数据
        this.disabled = false
        this.progressShow = false
        this.statusFlag = false
        this.percentage = 0
      }).catch(res => {
        this.disabled = false
        this.statusFlag = false
        this.progressShow = false
        this.percentage = 0
      })
    },
    getOneName () {
      this.disabledName = true
      this.nameIcon = 'el-icon-loading'
      this.lseajax.post(this.lseajax.baseurl + '/users/getOneName', {}).then((data) => {
        if (data.code === 200) {
          this.userData.nickname = data.data
        } else {
          this.lseutil.msg({
            msg: data.msg
          })
        }
        this.disabledName = false
        this.nameIcon = 'el-icon-refresh-right'
      }).catch(data => {
        this.disabledName = false
        this.nameIcon = 'el-icon-refresh-right'
      })
    },
    fileClick (ref) {
      this.$refs[ref].dispatchEvent(new MouseEvent('click'))
    },
    showBig (ref) {
      this.$refs[ref].dispatchEvent(new MouseEvent('click'))
    },
    goBack () {
      this.lseutil.goBack()
    },
    initAvatarSize () {
      let width = document.body.clientWidth
      if (width >= 1366) {
        this.avatarSize = 200
      } else if (width > 768) {
        this.avatarSize = 150
      } else if (width <= 768) {
        this.avatarSize = 100
      }
    }
  },
  mounted () {
    window.onresize = () => {
      this.initAvatarSize()
    }
  },
  created () {
    this.getUserInfo()
    this.initAvatarSize()
  }
}
</script>

<style scoped>
>>>.el-avatar img{
  margin: auto
}
</style>
